import { _pick, reduceToObject } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createBrandApiMWRouter } from "../../middleware/brand-api/brandAdminChecker";
import pageMW from "../../middleware/pager";
import {
  listBrandFanWithUserAndUserStats,
  updateBrandFan,
} from "../../service/brandFanService";
import { listAggsToUserRecentNewses } from "../../service/userPvLogService";
const router = createBrandApiMWRouter();

router.get(
  "brand-fans",
  "/brd/:brandId/fans",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { brandId } = ctx.params;
    let { keyword } = ctx.query;
    const { userId, limit, offset, ts } = ctx;

    const { total, items } = await listBrandFanWithUserAndUserStats(
      { brandId, keyword },
      {
        limit,
        offset,
        ts,
      }
    );
    const followerRecentNews = await listAggsToUserRecentNewses(
      items.map((it) => it.followerUserId)
    );
    const recentNewsMap = reduceToObject(
      followerRecentNews,
      (o) => o.userId,
      (o) => o.latestTime
    );

    ctx.body = {
      total,
      rows: items.map((it) => ({
        recentNews: recentNewsMap[it.followerUserId],
        ..._pick(
          it,
          "brandFanId",
          "aliasName",
          "followerUserNickName",
          "followerUserPic",
          "involveActivityCount",
          "viewCount",
          "payAmount"
        ),
      })),
    };
  }
);

// 备注粉丝名称
router.put("/brd/:brandId/fan/:brandFanId/alias", async (ctx: AppCTX, next) => {
  const { brandId, brandFanId } = ctx.params;
  const { aliasName } = ctx.request.body;
  const { userId } = ctx;

  const brandFan = await updateBrandFan({ brandFanId, aliasName });

  ctx.body = {
    ..._pick(brandFan, "brandFanId", "aliasName"),
  };
});

export default router;
